package com.sc.nft.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.sc.nft.admin.request.*;
import com.sc.nft.annotation.SysMemberLogin;
import com.sc.nft.dao.*;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.*;
import com.sc.nft.entity.vo.SecondOrderExportListVO;
import com.sc.nft.entity.vo.SecondOrderExportVO;
import com.sc.nft.enums.DigitalMarketTypeEnum;
import com.sc.nft.enums.MarketTypeEnum;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.enums.SecondWantBuyOrderTypeEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.SecondOrderService;
import com.sc.nft.service.StaticDataService;
import com.sc.nft.sup.ErrorCode;
import com.sc.nft.sup.PageResult;
import com.sc.nft.sup.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/admin/second")
@Api(tags = "二级市场管理")
public class SecondMarketAdminController {
    private final SecondCollectionConfigDao secondCollectionConfigDao;
    private final SecondCollectionDao secondCollectionDao;
    private final StaticDataService staticDataService;
    private final DigitalCollectionDao digitalCollectionDao;
    private final SecondOrderService secondOrderService;
    private final ShareProfitPanelDao shareProfitPanelDao;
    private final RedisTemplate redisTemplate;
    private final EquityPropsDao equityPropsDao;
    private final WantBuyOrderDao wantBuyOrderDao;

    @PostMapping(value = "/collectionList", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取添加藏品的列表", notes = "获取添加藏品的列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin

    public PageResult<AdminDigitalCollectionVO> collectionList(@Valid @RequestBody CollectionListAdminDTO collectionListAdminDTO) {
        return PageResult.success(digitalCollectionDao.getListByAdminPage(collectionListAdminDTO));
    }


    @PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加二级市场藏品(新增寄售藏品)", notes = "添加二级市场藏品", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result addSecondCollection(@Valid @RequestBody AddSecondCollectionRequest request) {
        if (!request.lockedPositionDecide()) {
            throw new GlobalRunTimeException(ErrorCode.LOCKED_POSITION);
        }
        if (ObjectUtil.isNotNull(secondCollectionConfigDao.getByCollectionId(request.getCollectionId()))) {
            return Result.fail("该藏品已经添加过了");
        }
        if (ObjectUtil.isNull(shareProfitPanelDao.getById(request.getShareProfitPanelId()))) {
            return Result.fail("未找到分润模板");
        }
        // 2024年7月3日 目前品牌孵化不允许添加gas费.
        if (request.getMarketType().equals(MarketTypeEnum.BRAND_INCUBATION)) {
            request.setGas(BigDecimal.ZERO);
        }

        //校验是否开启求购
        checkAddWantBuy(request);

        SecondCollectionConfig secondCollectionConfig = BeanUtil.toBean(request, SecondCollectionConfig.class);
        //手续费
        secondCollectionConfig.setCharge(request.getCharge().divide(Convert.toBigDecimal(100)));

        //校验参数
        checkSecondCollectionConfigPram(secondCollectionConfig);
        //品牌孵化 参数特别初始化
        if (request.getMarketType() == MarketTypeEnum.BRAND_INCUBATION) {
            //BigDecimal minAntiHoardPrice = userCollectionDao.getMinAntiHoardPrice(request.getCollectionId());
            //if(request.getStartPrice().compareTo(minAntiHoardPrice)  == -1){
            //    return Result.fail("起始价不能小于最小防囤价: 最小防囤价为:" + minAntiHoardPrice.stripTrailingZeros().toPlainString());
            //}

            BigDecimal upRatio = request.getUpRatio().divide(Convert.toBigDecimal(100));
            secondCollectionConfig.setUpRatio(upRatio);
            secondCollectionConfig.setCumulativeIncrease(upRatio);
            secondCollectionConfig.setMinPrice(secondCollectionConfig.getStartPrice());
            secondCollectionConfig.setMaxPrice(secondCollectionConfig.getStartPrice().add(secondCollectionConfig.getStartPrice().multiply(upRatio)));
            if (secondCollectionConfig.getIsDisassembly()) {
                secondCollectionConfig.setDisassemblyMultiple(ObjectUtil.isNull(secondCollectionConfig.getDisassemblyMultiple()) ? 0 : secondCollectionConfig.getDisassemblyMultiple());
                if (secondCollectionConfig.getDisassemblyMultiple() > 0) {
                    //拆配总额 = 起始金额 * 倍数
                    BigDecimal disassemblySum = secondCollectionConfig.getStartPrice().multiply(Convert.toBigDecimal(secondCollectionConfig.getDisassemblyMultiple()));
                    //String days=  Math.log((拆配/发行))/Math.log(1+增长率)
                    double log = BigDecimal.ONE.add(secondCollectionConfig.getUpRatio()).doubleValue();
                    double log2 = disassemblySum.divide(secondCollectionConfig.getMaxPrice(), 8, BigDecimal.ROUND_DOWN).stripTrailingZeros().doubleValue();
                    //拆配剩余天数
                    secondCollectionConfig.setLastDisassemblyDay(Convert.toInt(Convert.toBigDecimal(Math.log(log2)).divide(Convert.toBigDecimal(Math.log(log)), 0, BigDecimal.ROUND_UP).stripTrailingZeros()));
                }
            }

        } else {
            DigitalCollection ecologyCollection = digitalCollectionDao.getById(request.getCollectionId());
            if (ecologyCollection.getCollectionType() == DigitalMarketTypeEnum.ECOLOGY) {
                secondCollectionConfig.setConsensusUpTime(0);
                secondCollectionConfig.setConsensusDownTime(0);
                secondCollectionConfig.setConsensusMinPrice(secondCollectionConfig.getMinPrice());
                secondCollectionConfig.setConsensusMaxPrice(secondCollectionConfig.getMaxPrice());

            }
            secondCollectionConfig.setStartPrice(ObjectUtil.isNull(secondCollectionConfig.getStartPrice()) ? BigDecimal.ZERO : secondCollectionConfig.getStartPrice());
            secondCollectionConfig.setFloatingPrice(ObjectUtil.isNull(secondCollectionConfig.getStartPrice()) ? BigDecimal.ZERO : secondCollectionConfig.getStartPrice());
            secondCollectionConfig.setUpRatio(BigDecimal.ZERO);
        }
        secondCollectionConfig.setStatus(Boolean.FALSE);
        secondCollectionConfig.insert();
        return Result.success();
    }


    @PostMapping(value = "/edit", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "編輯二级市场藏品(新增寄售藏品)", notes = "編輯二级市场藏品", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result editSecondCollection(@Valid @RequestBody EditSecondCollectionRequest request) {
        if (!request.lockedPositionDecide()) {
            throw new GlobalRunTimeException(ErrorCode.LOCKED_POSITION);
        }
        SecondCollectionConfig secondCollectionConfig = secondCollectionConfigDao.getById(request.getId());
        if (ObjectUtil.isNull(secondCollectionConfig)) {
            return Result.fail("未找到藏品");
        }
        if (ObjectUtil.isNull(shareProfitPanelDao.getById(request.getShareProfitPanelId()))) {
            return Result.fail("未找到分润模板");
        }
        secondCollectionConfig.setShareProfitPanelId(request.getShareProfitPanelId());
        //如果数据库里的数据  该藏品是自由市场 并且 要修改成品牌孵化
        if (secondCollectionConfig.getMarketType() == MarketTypeEnum.FREE_MARKET && secondCollectionConfig.getMarketType() != request.getMarketType()) {
            return Result.fail("不能修改");
        }
        //上架中 不能修改
//        if(secondCollectionConfig.getStatus()){
//            return Result.fail("必须下架之后才能修改");
//        }

        // 判定当前藏品是否为版权藏品,如果是的话,则判定是否有用户在售卖.有的话,则不能修改.
        DigitalCollection byId = digitalCollectionDao.getById(secondCollectionConfig.getCollectionId());
        if (byId.getCollectionType().equals(DigitalMarketTypeEnum.COPYRIGHT)) {
            // 判定该商品是否有上架正在售卖的.
            if (secondCollectionDao.whetherAnItemIsOnConsignment(secondCollectionConfig.getCollectionId())) {
                throw new GlobalRunTimeException("当前有用户挂单不能修改");
            }
        }

        //校验是否开启求购
        checkEditWantBuy(request);

        SecondCollectionConfig updateSecondCollectionConfig = BeanUtil.toBean(request, SecondCollectionConfig.class);
        //参数校验
        checkSecondCollectionConfigPram(updateSecondCollectionConfig);

        //手续费
        updateSecondCollectionConfig.setCharge(request.getCharge().divide(Convert.toBigDecimal(100)));

        if (secondCollectionConfig.getMarketType() == MarketTypeEnum.BRAND_INCUBATION) {
            updateSecondCollectionConfig.setUpRatio(request.getUpRatio().divide(Convert.toBigDecimal(100)));
            //BigDecimal minAntiHoardPrice = userCollectionDao.getMinAntiHoardPrice(request.getCollectionId());
            //if(request.getStartPrice().compareTo(minAntiHoardPrice)  == -1){
            //    return Result.fail("起始价不能小于最小防囤价: 最小防囤价为:" + minAntiHoardPrice.stripTrailingZeros().toPlainString());
            //}

            //判断增长率是否修改
            boolean upRatioBoolean = secondCollectionConfig.getUpRatio().compareTo(updateSecondCollectionConfig.getUpRatio()) == 0;
            //判断起始价是否修改
            boolean startPriceBoolean = secondCollectionConfig.getStartPrice().compareTo(updateSecondCollectionConfig.getStartPrice()) == 0;
            //如果修改了起始价或者增长率  最大/小值 重置 拆配天数重置
            if (!upRatioBoolean || !startPriceBoolean) {
                updateSecondCollectionConfig.setMinPrice(updateSecondCollectionConfig.getStartPrice());
                updateSecondCollectionConfig.setMaxPrice(updateSecondCollectionConfig.getStartPrice().add(updateSecondCollectionConfig.getStartPrice().multiply(updateSecondCollectionConfig.getUpRatio())));
            }

            //重置拆配天数
            if (updateSecondCollectionConfig.getIsDisassembly() && updateSecondCollectionConfig.getDisassemblyMultiple() > 0) {
                //拆配总额 = 起始金额 * 倍数
                BigDecimal disassemblySum = updateSecondCollectionConfig.getStartPrice().multiply(Convert.toBigDecimal(updateSecondCollectionConfig.getDisassemblyMultiple()));
                //String days=  Math.log((拆配/发行))/Math.log(1+增长率)
                double log = BigDecimal.ONE.add(updateSecondCollectionConfig.getUpRatio()).doubleValue();
                double log2 = disassemblySum.divide(secondCollectionConfig.getMaxPrice(), 8, BigDecimal.ROUND_DOWN).stripTrailingZeros().doubleValue();
                //拆配剩余天数
                updateSecondCollectionConfig.setLastDisassemblyDay(Convert.toInt(Convert.toBigDecimal(Math.log(log2)).divide(Convert.toBigDecimal(Math.log(log)), 0, BigDecimal.ROUND_UP).stripTrailingZeros()));
            }

        } else {//初始值
//            updateSecondCollectionConfig.setUpRatio(ObjectUtil.isNull(secondCollectionConfig.getUpRatio()) ? BigDecimal.ZERO: secondCollectionConfig.getUpRatio());
            updateSecondCollectionConfig.setStartPrice(ObjectUtil.isNull(secondCollectionConfig.getStartPrice()) ? BigDecimal.ZERO : secondCollectionConfig.getStartPrice());
            updateSecondCollectionConfig.setFloatingPrice(ObjectUtil.isNull(secondCollectionConfig.getStartPrice()) ? BigDecimal.ZERO : secondCollectionConfig.getStartPrice());
            updateSecondCollectionConfig.setUpRatio(BigDecimal.ZERO);
//            BigDecimal freeUpRatio = secondCollectionConfig.getFreeUpRatio();
//            BigDecimal freeDownRatio = secondCollectionConfig.getFreeDownRatio();
//            BigDecimal floatingPrice = secondCollectionConfig.getFloatingPrice();
//
//            freeDownRatio = (Convert.toBigDecimal(100).subtract(freeDownRatio)).divide(Convert.toBigDecimal(100), 2, BigDecimal.ROUND_DOWN);
//            freeUpRatio = (Convert.toBigDecimal(100).add(freeUpRatio)).divide(Convert.toBigDecimal(100), 2, BigDecimal.ROUND_DOWN);

            updateSecondCollectionConfig.setConsensusMinPrice(request.getConsensusMinPrice());
            updateSecondCollectionConfig.setConsensusMaxPrice(request.getConsensusMaxPrice());
        }
        updateSecondCollectionConfig.updateById();
        return Result.success();
    }

    @PostMapping(value = "/page", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "允许寄售藏品列表(寄售藏品配置)", notes = "允许寄售藏品列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<SecondCollectionDTO> page(@Valid @RequestBody CollectionIdRequest request) {
        return PageResult.success(secondCollectionConfigDao.pageSecond(request.getFirstTitle(), request.getPageNo(), request.getPageSize(), request.getMarketType(), request.getNewOrOld()));
    }

    @PostMapping(value = "/getSecondCollectionList", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "交易藏品列表", notes = "交易藏品列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result<List<SecondOrderCollectionListDTO>> collectionList(@Valid @RequestBody collectionPageRequest request) {
        return Result.success(secondOrderService.collectionList(request.getMarketType()));
    }

    @PostMapping(value = "/dealPage", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "交易列表", notes = "交易列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<SecondOrderDTO> dealPage(@Valid @RequestBody SecondOrderPageRequest request) {
        return PageResult.success(secondOrderService.adminPage(request.getStartTime(), request.getEndTime(), request.getBuyUserTel(), request.getSaleUserTel(), request.getMarketType(), request.getFirstTitle(), request.getPageNo(), request.getPageSize()));
    }


    @PostMapping(value = "/collectionExport", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "二级市场交易列表导出", notes = "二级市场交易列表导出", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result<SecondOrderExportVO> collectionExport(@Valid @RequestBody CollectionExportRequest request) {
        if (CollUtil.isEmpty(request.getCollectionIdList()) && (ObjectUtil.isNull(request.getEndTime()) || ObjectUtil.isNull(request.getStartTime()))) {
            return Result.fail("藏品标题筛选和交易时间筛选不能都为空");
        }
        SecondOrderExportVO result = new SecondOrderExportVO();
        if (MarketTypeEnum.BRAND_INCUBATION == MarketTypeEnum.getMarketTypeEnum(request.getMarketType())) {
            result.setExcelName("品牌孵化订单明细" + DateUtil.format(DateUtil.date(), "yyyy年MM月dd日") + ".xlsx");
        } else {
            result.setExcelName("自由市场订单明细" + DateUtil.format(DateUtil.date(), "yyyy年MM月dd日") + ".xlsx");
        }

        List<SecondOrderExportListVO> secondOrderExportListVOS = secondOrderService.collectionExport(request.getCollectionIdList(), request.getMarketType(), request.getStartTime(), request.getEndTime());
        result.setSecondOrderExportListVOList(secondOrderExportListVOS);
        return Result.success(result);
    }

    @PostMapping(value = "/conSignPage", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "寄售藏品列表(寄售列表)", notes = "寄售藏品列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<SecondConSignCollectionDTO> conSignPage(@Valid @RequestBody ConsignPageRequest request) {
        return PageResult.success(secondCollectionDao.getAdminConsignPage(request.getDealStartTime(), request.getDealEndTime(), request.getPhone(), request.getStatus(), request.getPageNo(), request.getPageSize(), request.getMarketType()));
    }

    @PostMapping(value = "/marketConfig", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "市场配置(修改寄售市场配置)", notes = "市场配置", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result marketConfig(@Valid @RequestBody MarketConfigDTO request) {
        StaticData staticData = staticDataService.getByType("market_config");
        if (ObjectUtil.isNull(staticData)) {
            staticData = new StaticData();
        }
        staticData.setIsShowInterface(0);
        staticData.setIsShowManage(0);
        staticData.setRemark("市场配置可交易时间");
        staticData.setValue(JSONObject.toJSONString(request));
        staticData.setType("market_config");
        staticData.insertOrUpdate();
        String key = StrUtil.format("{}:{}", RedisKeyEnum.STATIC_DATA_TYPE, "market_config");
        redisTemplate.delete(key);
        return Result.success();
    }

    @PostMapping(value = "/getFreeMarketConfig", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取市场配置(获取自由市场配置)", notes = "获取市场配置", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<MarketConfigDTO> getFreeMarketConfig() {
        StaticData staticData = staticDataService.getByType("free_market_config");
        if (ObjectUtil.isNull(staticData)) {
            return Result.success();
        }
        return Result.success(JSONObject.parseObject(staticData.getValue(), MarketConfigDTO.class));
    }

    @PostMapping(value = "/freeMarketConfig", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "市场配置(修改自由市场配置)", notes = "市场配置", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result freeMarketConfig(@Valid @RequestBody MarketConfigDTO request) {
        StaticData staticData = staticDataService.getByType("free_market_config");
        if (ObjectUtil.isNull(staticData)) {
            staticData = new StaticData();
        }
        staticData.setIsShowInterface(0);
        staticData.setIsShowManage(0);
        staticData.setRemark("市场配置可交易时间");
        staticData.setValue(JSONObject.toJSONString(request));
        staticData.setType("free_market_config");
        staticData.insertOrUpdate();
        String key = StrUtil.format("{}:{}", RedisKeyEnum.STATIC_DATA_TYPE, "free_market_config");
        redisTemplate.delete(key);
        return Result.success();
    }


    @PostMapping(value = "/getMarketConfig", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取市场配置(获取寄售市场配置)", notes = "获取市场配置", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result<MarketConfigDTO> getMarketConfig() {
        StaticData staticData = staticDataService.getByType("market_config");
        if (ObjectUtil.isNull(staticData)) {
            return Result.success();
        }
        return Result.success(JSONObject.parseObject(staticData.getValue(), MarketConfigDTO.class));
    }


    @PostMapping(value = "/enable", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "启动藏品(上架)", notes = "启动藏品", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result enable(@Valid @RequestBody IdRequest request) {
        SecondCollectionConfig byCollectionId = secondCollectionConfigDao.getById(request.getId());
        if (ObjectUtil.isNull(byCollectionId)) {
            return Result.fail("未找到二级藏品记录");
        }
        byCollectionId.setStatus(true);
        byCollectionId.updateById();
        return Result.success();
    }

    @PostMapping(value = "/disable", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "禁用藏品(下架)", notes = "禁用藏品", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result disable(@Valid @RequestBody IdRequest request) {
        SecondCollectionConfig byCollectionId = secondCollectionConfigDao.getById(request.getId());
        if (ObjectUtil.isNull(byCollectionId)) {
            return Result.fail("未找到二级藏品记录");
        }

        List<SecondCollection> list = secondCollectionDao.getListByCollectionIdWithOnSales(byCollectionId.getCollectionId());
        if (list.size() > 0) {
            return Result.fail("此藏品还有存在上架中的 不能下架");
        }

        if (byCollectionId.getMarketType() == MarketTypeEnum.BRAND_INCUBATION) {
            //校验时间
            StaticData staticData = staticDataService.getByType("market_config");
            MarketConfigDTO marketConfigDTO = JSONObject.parseObject(staticData.getValue(), MarketConfigDTO.class);
            DateTime now = DateTime.now();
            String dateStr = now.toString("yyyy-MM-dd");
            DateTime buyStartDate1 = DateUtil.parse(dateStr + " " + marketConfigDTO.getBuyStartTimeOne(), "yyyy-MM-dd HH:mm");
            DateTime buyEndDate1 = DateUtil.parse(dateStr + " " + marketConfigDTO.getBuyEndTimeOne(), "yyyy-MM-dd HH:mm");
            DateTime buyStartDate2 = DateUtil.parse(dateStr + " " + marketConfigDTO.getBuyStartTimeTwo(), "yyyy-MM-dd HH:mm");
            DateTime buyEndDate2 = DateUtil.parse(dateStr + " " + marketConfigDTO.getBuyEndTimeTwo(), "yyyy-MM-dd HH:mm");

            if (((now.after(buyStartDate1) && now.before(buyEndDate1)) || (now.after(buyStartDate2) && now.before(buyEndDate2)))) {
                return Result.fail("购买时间不能下架");
            }

            DateTime billingStartTimeOne = DateUtil.parse(dateStr + " " + marketConfigDTO.getBillingStartTimeOne(), "yyyy-MM-dd HH:mm");
            DateTime billingEndTimeOne = DateUtil.parse(dateStr + " " + marketConfigDTO.getBillingEndTimeOne(), "yyyy-MM-dd HH:mm");
            DateTime billingStartTimeTwo = DateUtil.parse(dateStr + " " + marketConfigDTO.getBillingStartTimeTwo(), "yyyy-MM-dd HH:mm");
            DateTime billingEndTimeTwo = DateUtil.parse(dateStr + " " + marketConfigDTO.getBillingEndTimeTwo(), "yyyy-MM-dd HH:mm");
            if (((now.after(billingStartTimeOne) && now.before(billingEndTimeOne)) || (now.after(billingStartTimeTwo) && now.before(billingEndTimeTwo)))) {
                return Result.fail("上架时间不能下架");
            }
        }

        Assert.isTrue(CollectionUtil.isEmpty(wantBuyOrderDao.releaseList(SecondWantBuyOrderTypeEnum.COLLECTION, byCollectionId.getCollectionId())), () -> new GlobalRunTimeException("当前有求购订单，无法进行下架"));

        byCollectionId.setStatus(false);
        byCollectionId.updateById();
        return Result.success();
    }


    @PostMapping(value = "/toFreeMarket", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "品牌孵化转自由", notes = "品牌孵化转自由", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result toFreeMarket(@Valid @RequestBody ToFreeMarketRequest request) {
        SecondCollectionConfig secondCollectionConfig = secondCollectionConfigDao.getById(request.getId());

        if (ObjectUtil.isNull(secondCollectionConfig)) {
            return Result.fail("未找到二级藏品记录");
        }

        if (secondCollectionConfig.getMarketType() != MarketTypeEnum.BRAND_INCUBATION) {
            return Result.fail("只有品牌孵化才可以转自由市场");
        }

//        if(secondCollectionConfig.getStatus()){
//            return Result.fail("上架中的配置不能修改");
//        }

        List<SecondCollection> list = secondCollectionDao.getListByCollectionIdWithOnSales(secondCollectionConfig.getCollectionId());
        if (list.size() > 0) {
            return Result.fail("此藏品还有存在上架中的 不能修改");
        }
        secondCollectionConfig.setMarketType(MarketTypeEnum.FREE_MARKET);
        secondCollectionConfig.setCharge(request.getCharge().divide(Convert.toBigDecimal(100)));
        secondCollectionConfig.setFloatingPrice(request.getFloatingPrice());
        secondCollectionConfig.setMinPrice(request.getMinPrice());
        secondCollectionConfig.setMaxPrice(request.getMaxPrice());
        secondCollectionConfig.setLockedPositionHour(request.getLockedPositionHour());
        secondCollectionConfig.setIsLockedPosition(request.getIsLockedPosition());
        secondCollectionConfig.setLockedPositionType(request.getLockedPositionType());
        secondCollectionConfig.setLockedPositionTime(request.getLockedPositionTime());
        secondCollectionConfig.setPlatformShow(request.getPlatformShow());
        secondCollectionConfig.setBrandShow(request.getBrandShow());
        secondCollectionConfig.setFirmShow(request.getFirmShow());
        secondCollectionConfig.setGas(request.getGas());
        secondCollectionConfig.setShareProfitPanelId(request.getShareProfitPanelId());
        secondCollectionConfig.updateById();
        return Result.success();
    }


    private void checkSecondCollectionConfigPram(SecondCollectionConfig secondCollectionConfig) {
        if (secondCollectionConfig.getMarketType() == MarketTypeEnum.BRAND_INCUBATION) {
            if (ObjectUtil.isNull(secondCollectionConfig.getStartPrice())) {
                throw new GlobalRunTimeException("起始价格不能为空");
            }
            if (ObjectUtil.isNull(secondCollectionConfig.getUpRatio())) {
                throw new GlobalRunTimeException("增长率不能为空");
            }

            if (ObjectUtil.isNull(secondCollectionConfig.getIsDisassembly())) {
                throw new GlobalRunTimeException("是否开启拆配不能为空");
            }

            if (secondCollectionConfig.getIsDisassembly()) {
                if (ObjectUtil.isNull(secondCollectionConfig.getDisassemblyMultiple())) {
                    throw new GlobalRunTimeException("拆配倍数不能为空");
                }
            }

            if (ObjectUtil.isNull(secondCollectionConfig.getBuyShares())) {
                throw new GlobalRunTimeException("用户购买份额不能为空");
            }

            if (ObjectUtil.isNull(secondCollectionConfig.getConsignExplanation())) {
                throw new GlobalRunTimeException("寄售规则不能为空");
            }

            if (secondCollectionConfig.getCharge().compareTo(BigDecimal.ZERO) == -1 || secondCollectionConfig.getCharge().compareTo(new BigDecimal("100")) == 1) {
                throw new GlobalRunTimeException("增长率范围不正确");
            }

            if (secondCollectionConfig.getBuyShares() < 0) {
                throw new GlobalRunTimeException("用户购买份额范围不正确");
            }
            if (ObjectUtil.isNull(secondCollectionConfig.getIncubationCycle())) {
                throw new GlobalRunTimeException("孵化周期不能为空");
            }
            if (secondCollectionConfig.getIncubationCycle() <= 0) {
                throw new GlobalRunTimeException("孵化周期需要大于0");
            }
        } else {
            if (ObjectUtil.isNull(secondCollectionConfig.getMinPrice())) {
                throw new GlobalRunTimeException("价格区间最小值不能为空");
            }
            if (ObjectUtil.isNull(secondCollectionConfig.getMaxPrice())) {
                throw new GlobalRunTimeException("价格区间最大值不能为空");
            }
            if (NumberUtil.isLess(secondCollectionConfig.getMinPrice(), BigDecimal.ONE)) {
                throw new GlobalRunTimeException("价格区间最小值不能小于1");
            }
            if (NumberUtil.isGreater(secondCollectionConfig.getMaxPrice(), NumberUtil.toBigDecimal("99999"))) {
                throw new GlobalRunTimeException("价格区间最大值不能大于99999");
            }
            if (NumberUtil.isLess(secondCollectionConfig.getMaxPrice(), secondCollectionConfig.getMinPrice())) {
                throw new GlobalRunTimeException("价格区间最大值不能小于最小值");
            }
            if (ObjectUtil.isNull(secondCollectionConfig.getStartPrice())) {
                throw new GlobalRunTimeException("起始价格不能为空");
            }
            if (NumberUtil.isLess(secondCollectionConfig.getStartPrice(), BigDecimal.ZERO)) {
                throw new GlobalRunTimeException("起始价格不能小于0");
            }
        }
    }

    /**
     * 校验是否开启求购
     *
     * @param request
     */
    private void checkAddWantBuy(AddSecondCollectionRequest request) {
        if (!request.getEnableWantBuy()) {
            return;
        }
        Assert.notNull(request.getMinPrice(), () -> new GlobalRunTimeException("最低求购价格不能为空"));
        Assert.notNull(request.getMaxPrice(), () -> new GlobalRunTimeException("最高求购价格不能为空"));
        Assert.isTrue(request.getMinWantBuyPrice().compareTo(request.getMaxWantBuyPrice()) <= 0, () -> new GlobalRunTimeException("最高求购价格不能低于最低求购价格"));
        Assert.notNull(request.getWantBuyQuantity(), () -> new GlobalRunTimeException("单次最高求购价格不能为空"));
        Assert.isTrue(request.getWantBuyQuantity() > 0, () -> new GlobalRunTimeException("单次最高求购价格必须大于0"));
        Assert.notNull(request.getEnableWantBuyHoldCondition(), () -> new GlobalRunTimeException("求购持有条件不能为空"));
        Assert.notNull(request.getEnableWantBuyConsumeProp(), () -> new GlobalRunTimeException("求购消耗道具不能为空"));
        if (request.getEnableWantBuyHoldCondition()) {
            Assert.notNull(request.getWantBuyHoldCollectionId(), () -> new GlobalRunTimeException("持有藏品不能为空"));
            Assert.isFalse(Objects.equals(request.getCollectionId(), request.getWantBuyHoldCollectionId()), () -> new GlobalRunTimeException("持有藏品不能与集售藏品一致"));
            DigitalCollection digitalCollection = digitalCollectionDao.getById(request.getWantBuyHoldCollectionId());
            Assert.notNull(digitalCollection, () -> new GlobalRunTimeException("持有藏品不存在"));
        }
        if (request.getEnableWantBuyConsumeProp()) {
            Assert.notNull(request.getWantBuyConsumePropId(), () -> new GlobalRunTimeException("消耗道具不能为空"));
            Assert.notNull(request.getWantBuyConsumePropQuantity(), () -> new GlobalRunTimeException("消耗道具数量不能为空"));
            Assert.isTrue(request.getWantBuyConsumePropQuantity() > 0, () -> new GlobalRunTimeException("消耗道具数量必须大于0"));
            EquityProps equityProps = equityPropsDao.getById(request.getWantBuyConsumePropId());
            Assert.notNull(equityProps, () -> new GlobalRunTimeException("消耗道具不存在"));
            Assert.isTrue(equityProps.getStatus(), () -> new GlobalRunTimeException("消耗道具已下架"));
        }
    }

    /**
     * 校验是否开启求购
     *
     * @param request
     */
    private void checkEditWantBuy(EditSecondCollectionRequest request) {
        if (!request.getEnableWantBuy()) {
            return;
        }
        Assert.notNull(request.getMinPrice(), () -> new GlobalRunTimeException("最低求购价格不能为空"));
        Assert.notNull(request.getMaxPrice(), () -> new GlobalRunTimeException("最高求购价格不能为空"));
        Assert.isTrue(request.getMinWantBuyPrice().compareTo(request.getMaxWantBuyPrice()) <= 0, () -> new GlobalRunTimeException("最高求购价格不能低于最低求购价格"));
        Assert.notNull(request.getWantBuyQuantity(), () -> new GlobalRunTimeException("单次最高求购价格不能为空"));
        Assert.isTrue(request.getWantBuyQuantity() > 0, () -> new GlobalRunTimeException("单次最高求购价格必须大于0"));
        Assert.notNull(request.getEnableWantBuyHoldCondition(), () -> new GlobalRunTimeException("求购持有条件不能为空"));
        Assert.notNull(request.getEnableWantBuyConsumeProp(), () -> new GlobalRunTimeException("求购消耗道具不能为空"));
        if (request.getEnableWantBuyHoldCondition()) {
            Assert.notNull(request.getWantBuyHoldCollectionId(), () -> new GlobalRunTimeException("持有藏品不能为空"));
            Assert.isFalse(Objects.equals(request.getCollectionId(), request.getWantBuyHoldCollectionId()), () -> new GlobalRunTimeException("持有藏品不能与集售藏品一致"));
            DigitalCollection digitalCollection = digitalCollectionDao.getById(request.getWantBuyHoldCollectionId());
            Assert.notNull(digitalCollection, () -> new GlobalRunTimeException("持有藏品不存在"));
        }
        if (request.getEnableWantBuyConsumeProp()) {
            Assert.notNull(request.getWantBuyConsumePropId(), () -> new GlobalRunTimeException("消耗道具不能为空"));
            Assert.notNull(request.getWantBuyConsumePropQuantity(), () -> new GlobalRunTimeException("消耗道具数量不能为空"));
            Assert.isTrue(request.getWantBuyConsumePropQuantity() > 0, () -> new GlobalRunTimeException("消耗道具数量必须大于0"));
            EquityProps equityProps = equityPropsDao.getById(request.getWantBuyConsumePropId());
            Assert.notNull(equityProps, () -> new GlobalRunTimeException("消耗道具不存在"));
            Assert.isTrue(equityProps.getStatus(), () -> new GlobalRunTimeException("消耗道具已下架"));
        }
    }

}
